package com.jiawa.train.business.controller.web;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jiawa.train.business.req.ConfirmOrderDoReq;
import com.jiawa.train.business.service.BeforeConfirmOrderService;
import com.jiawa.train.business.service.ConfirmOrderService;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.Result;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/web/confirmOrder")
public class ConfirmOrderController {

    @Resource
    private BeforeConfirmOrderService beforeConfirmOrderService;

    @Resource
   private RedisTemplate<String,String> stringRedisTemplate;

    @Resource
    private ConfirmOrderService confirmOrderService;

//    @SentinelResource(value = "doConfirm", blockHandler = "doConfirmBlock")
    @PostMapping("/do")
    public Result doConfirmOrder(@Valid @RequestBody ConfirmOrderDoReq req) {
        //图形验证码校验
        String imageCode = req.getImageCode();
        String imageCodeToken = req.getImageCodeToken();
        Object redisImageCodeObj = stringRedisTemplate.opsForValue().get(imageCodeToken);
        if (ObjectUtil.isEmpty(redisImageCodeObj)) {
            return Result.error("验证码已过期");
        }
        String redisImageCode = (String) redisImageCodeObj;
        log.info("imageCode: {}, redisImageCode: {}", imageCode, redisImageCode);
        if (ObjectUtil.isEmpty(redisImageCode)) {
            return Result.error("验证码已过期");
        }
        if (!imageCode.equalsIgnoreCase(redisImageCode)) {
            return Result.error("验证码不正确");
        } else {
            stringRedisTemplate.delete(imageCodeToken);
        }
        Long confirmOrderId = beforeConfirmOrderService.beforeConfirmOrder(req);
        return Result.success(String.valueOf(confirmOrderId));
    }
    public Result doConfirmBlock(ConfirmOrderDoReq req, BlockException e){
        log.error("ConfirmOrderController购票请求被限流了，规则类型: {}, 请求: {}", e.getRule(), req, e); // 将异常信息也打印出来
        return Result.error(BusinessExceptionEnum.CONFIRM_ORDER_FLOW_EXCEPTION.getDesc());
    }
    @GetMapping("/queryLineCount/{id}")
    public Result queryLineCount(@PathVariable Long id) {
        Integer count = confirmOrderService.queryLineCount(id);
        return Result.success(count);
    }
}
